package jcu.ict.profaid;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class FormListCourse extends Activity{
	private static CourseDbAdapter cdb;
	private SessionManager session;
	private ListView lv_course;
	private MyAdapter favContexted;
	private AdapterContextMenuInfo menuInfo;
	private EditText inputSearch;
	private String user_id;
	private ArrayList<String> arr_sort= new ArrayList<String>();
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		session = new SessionManager(getApplicationContext());
		session.checkLogin();		
		
	    setContentView(R.layout.form_my_subject);
	    
	    Bundle bundle = this.getIntent().getExtras();
	    user_id = (String) bundle.getCharSequence("setUserId");

	    lv_course = (ListView)findViewById(R.id.lstMyQuestion);
	    
	    cdb = new CourseDbAdapter(getBaseContext());

	    cdb.open();
	    
	    final ArrayList<Object> listCourse = PopulateList(null);
	    favContexted = new MyAdapter(this, R.layout.listview_display, R.id.txtUp, listCourse);
	    lv_course.setAdapter(favContexted);

	    registerForContextMenu(lv_course);
	    
	    inputSearch = (EditText) findViewById(R.id.edtSearch);
	    
		inputSearch.addTextChangedListener(new TextWatcher() {
		     
		    @Override
		    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
		        // When user changed the Text
		    	favContexted.getFilter().filter(cs);
		    }
		     
		    @Override
		    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
		            int arg3) {
		        // TODO Auto-generated method stub
		         
		    }
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	   
	    lv_course.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String i = arg0.getItemAtPosition(arg2).toString();
				
				Intent in = new Intent(FormListCourse.this, MainQuestion.class);
				
				Bundle bundle = new Bundle();
				
				String[] info = i.split(","); 
		        String[] updateId = info[4].split("]");
		        
		        String id_course = updateId[0];
	            bundle.putCharSequence("setInfoCourse", id_course);
	            bundle.putCharSequence("setUserId", user_id);
	            in.putExtras(bundle);
				startActivity(in);
            }
        });
	    
	}
	
	private ArrayList<Object> PopulateList(String abc) {
		// TODO Auto-generated method stub
		SQLiteCursor krsr = null;
		try{
			krsr = (SQLiteCursor) cdb.getAllCourse(user_id);
				
		}catch(Exception ex){
			Log.e("salah",ex.toString());
			return null;
		}
		
		ArrayList<Object> queryResult = new ArrayList<Object>();
		final int colCnt = krsr.getColumnCount();
		
		while (krsr.moveToNext()) {
            ArrayList<Object> satuRow = new ArrayList<Object>();
            for (int i = 0; i < colCnt; i++) {
                /**
                 * In android 2.2 isNull is not exclusive so we need elseif's
                 */
                if (krsr.isNull(i)) {
                    satuRow.add("");
                } else if (krsr.isString(i)) {
                    satuRow.add(krsr.getString(i));
                } else if (krsr.isLong(i)) { // integer
                    satuRow.add(krsr.getLong(i));
                } else if (krsr.isFloat(i)) { // real
                    satuRow.add(krsr.getDouble(i));
                } else if (krsr.isBlob(i)) {
                    satuRow.add(krsr.getBlob(i));
                }
            }
            queryResult.add(satuRow);
        }
        krsr.close();
		return queryResult;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);

		menu.add("Edit");
		menu.add("Delete");
	}

	public boolean onContextItemSelected(MenuItem item) {
		menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
		if (item.getTitle() == "Edit") {
			ListAdapter adapter = lv_course.getAdapter();
			Object obj = adapter.getItem(menuInfo.position);
			String x = obj.toString();

			String[] info = x.split(","); 
	        String[] updateId = info[4].split("]");
	        
	        String id_course = updateId[0];
            
			Intent in = new Intent(FormListCourse.this,
					FormEditCourse.class);
			Bundle bundle = new Bundle();
			bundle.putString("setInfoCourse", id_course);
			bundle.putCharSequence("setUserId", user_id);
			in.putExtras(bundle);
			startActivity(in);
			finish();
		}
			else if (item.getTitle() == "Delete") {
				ListAdapter adapter = lv_course.getAdapter();
				Object obj = adapter.getItem(menuInfo.position);
				String x = obj.toString();

				String[] info = x.split(","); 
		        String[] updateId = info[4].split("]");
		        
		        final String id_course = updateId[0];

				AlertDialog.Builder builder = new AlertDialog.Builder(
						FormListCourse.this);
				builder.setMessage("Are you sure want to Delete this question?")
						.setCancelable(false)
						.setPositiveButton("Yes",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										
										cdb.open();

										if (cdb.DeleteCourse(id_course) > 0) {
											Toast.makeText(getBaseContext(),
													"Delete Success!!",
													Toast.LENGTH_LONG).show();
										} else {
											Toast.makeText(
													getBaseContext(),
													"Delete Failed, Please Try Again!",
													Toast.LENGTH_LONG).show();
										}

										ListAdapter adapter = lv_course
												.getAdapter();
										Object obj = adapter
												.getItem(menuInfo.position);

										/* Remove it from the list. */
										favContexted.remove(obj);

										cdb.close();          
									}
								})

						.setNegativeButton("No",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								}).show();
				
			} 
		return true;
	}  
}
